#include <jni.h>
#include <stdio.h>
#include "Prompt.h"

/*
GetStringChars
ReleaseStringChars
Obtains or releases a pointer to the contents of a string in Unicode format. May return a copy of the string.

GetStringUTFChars
ReleaseStringUTFChars
Obtains or releases a pointer to the contents of a string in UTF-8 format. May return a copy of the string.

GetStringLength 
Returns the number of Unicode characters in the string.

GetStringUTFLength 
Returns the number of bytes needed (not including the trailing 0) to represent a string in the UTF-8 format.

NewString 
Creates a java.lang.String instance that contains the same sequence of characters as the given Unicode C string.

NewStringUTF 
Creates a java.lang.String instance that contains the same sequence of characters as the given UTF-8 encoded C string.

GetStringCritical
ReleaseStringCritical 
Obtains a pointer to the contents of a string in Unicode format. May return a copy of the string. Native code must not block between a pair of Get/ReleaseStringCritical calls.

GetStringRegion
SetStringRegion
Copies the contents of a string to or from a preallocated C buffer in the Unicode format.

GetStringUTFRegion
SetStringUTFRegion
Copies the content of a string to or from a preallocated C buffer in the UTF-8 format.


Choosing among the JNI String Functions:
		1.2 and beyond
Targeting			   preallocated           		GetStringRegion
release 1.1 or  ------------------------>C string buffer,  --------Y--------->SetStringRegion
1.2?			                small fixed-size		GetStringUTFRegion
   |				  strings, or small		SetStringUTFRegion
   | 1.1 or both			  substrings?
   |					|
   |					N
   |					|
   |					v
   |				Any blocking or
   |				JNI calls while ------------N-------->GetStringCritical
   |				accessing string  		ReleaseStringCritical
   |				contents?
   |					|
   |					Y
   |					|
   |					v
   |				GetStringChars
   |				ReleaseStringChars
   ---------------------------------------->	GetStringUTFChars
   				ReleaseStringUTFChars

*/
JNIEXPORT jstring JNICALL Java_Prompt_getLine (JNIEnv * env, jobject obj, jstring prompt) 
{
#if 0
	char buf[128] = {0};
	const jbyte *str;
	str = (*env)->GetStringUTFChars(env, prompt, NULL);//会给字符串分配内存
	if (str == NULL) {//会抛出OutOfMemoryError异常到java层
		return NULL;
	}
	printf("%s\n", str);
	(*env)->ReleaseStringUTFChars(env, prompt, str);//释放内存
	scanf("%s", buf);

	return (*env)->NewStringUTF(env, buf);//会分配内存构造java.lang.String实例，失败则抛出
						//OutOfMemoryError异常到java层，并返回NULL
#else
	char outbuf[128], inbuf[128];	
	int len = (*env)->GetStringLength(env, prompt);
	(*env)->GetStringUTFRegion(env, prompt, 0, len, outbuf);
	printf("%s\n", outbuf);
	scanf("%s", inbuf);
	return (*env)->NewStringUTF(env, inbuf);
#endif						
}